// pages/meeting-form/meeting-form.js
const api = require('../../utils/api.js');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 表单数据
    formData: {
      meetingTitle: '',
      meetingDate: '',
      meetingDateValue: null,
      meetingTime: '',
      meetingTimeValue: null,
      participantCount: '',
      meetingContent: '',
      keyPoints: '',
      decisions: '',
      actionItems: ''
    },
    // 日期选择器显示
    showDatePicker: false,
    dateYears: [],
    dateMonths: [],
    dateDays: [],
    currentDateValue: [0, 0, 0], // 年月日的索引
    // 时间选择器显示
    showTimePicker: false,
    timeHours: [],
    timeMinutes: [],
    currentTimeValue: [0, 0], // 时分的索引
    // 人数选择器选项
    countOptions: [
      '2-5人', '6-10人', '11-20人', '21-50人', '50人以上'
    ],
    showCountPicker: false,
    currentCountIndex: 0, // 当前选中的人数索引
    // 日期选择器的范围限制
    minDate: new Date('2020-01-01').getTime(),
    maxDate: new Date('2030-12-31').getTime(),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: '会议纪要生成'
    });
    
    // 初始化日期和时间选择器数据
    this.initDateTimePicker();
    
    // 设置默认日期为今天
    const today = new Date();
    const month = today.getMonth() + 1;
    const day = today.getDate();
    const monthStr = month < 10 ? '0' + month : month;
    const dayStr = day < 10 ? '0' + day : day;
    const dateStr = `${today.getFullYear()}-${monthStr}-${dayStr}`;
    
    this.setData({
      'formData.meetingDate': dateStr,
      'formData.meetingDateValue': today.getTime(), // 添加时间戳用于选择器
      'formData.meetingTimeValue': new Date().getTime() // 添加默认时间
    });
  },

  /**
   * 初始化日期时间选择器数据
   */
  initDateTimePicker() {
    const currentYear = new Date().getFullYear();
    const years = [];
    const months = [];
    const days = [];
    const hours = [];
    const minutes = [];

    // 生成年份数组（当前年份前后5年）
    for (let i = currentYear - 5; i <= currentYear + 5; i++) {
      years.push(i);
    }

    // 生成月份数组
    for (let i = 1; i <= 12; i++) {
      months.push(i);
    }

    // 生成日期数组（默认31天，后续会根据月份调整）
    for (let i = 1; i <= 31; i++) {
      days.push(i);
    }

    // 生成小时数组（手动补零）
    for (let i = 0; i < 24; i++) {
      hours.push(i < 10 ? '0' + i : String(i));
    }

    // 生成分钟数组（每5分钟一个选项，手动补零）
    for (let i = 0; i < 60; i += 5) {
      minutes.push(i < 10 ? '0' + i : String(i));
    }

    this.setData({
      dateYears: years,
      dateMonths: months,
      dateDays: days,
      timeHours: hours,
      timeMinutes: minutes
    });
  },

  /**
   * 输入框内容变化
   */
  onInputChange(event) {
    const { field } = event.currentTarget.dataset;
    const { value } = event.detail;
    
    this.setData({
      [`formData.${field}`]: value
    });
  },

  /**
   * 显示日期选择器
   */
  showDatePicker() {
    // 获取当前日期并设置选择器的默认值
    const currentDate = this.data.formData.meetingDate;
    if (currentDate) {
      const parts = currentDate.split('-');
      const year = parseInt(parts[0]);
      const month = parseInt(parts[1]);
      const day = parseInt(parts[2]);
      
      const yearIndex = this.data.dateYears.indexOf(year);
      const monthIndex = this.data.dateMonths.indexOf(month);
      const dayIndex = this.data.dateDays.indexOf(day);
      
      this.setData({
        currentDateValue: [
          yearIndex >= 0 ? yearIndex : 5, // 默认当前年份
          monthIndex >= 0 ? monthIndex : new Date().getMonth(),
          dayIndex >= 0 ? dayIndex : new Date().getDate() - 1
        ],
        showDatePicker: true
      });
    } else {
      // 默认今天
      const today = new Date();
      const yearIndex = this.data.dateYears.indexOf(today.getFullYear());
      this.setData({
        currentDateValue: [
          yearIndex >= 0 ? yearIndex : 5,
          today.getMonth(),
          today.getDate() - 1
        ],
        showDatePicker: true
      });
    }
  },

  /**
   * 日期选择器滚动变化
   */
  onDateChange(event) {
    const { value } = event.detail;
    this.setData({
      currentDateValue: value
    });
  },

  /**
   * 确认选择日期
   */
  onDateConfirm() {
    const currentDateValue = this.data.currentDateValue;
    const yearIndex = currentDateValue[0];
    const monthIndex = currentDateValue[1];
    const dayIndex = currentDateValue[2];
    
    const year = this.data.dateYears[yearIndex];
    const month = this.data.dateMonths[monthIndex];
    const day = this.data.dateDays[dayIndex];
    
    // 手动补零，避免padStart兼容性问题
    const monthStr = month < 10 ? '0' + month : month;
    const dayStr = day < 10 ? '0' + day : day;
    const dateStr = `${year}-${monthStr}-${dayStr}`;
    
    console.log('onDateConfirm - year:', year, 'month:', month, 'day:', day, 'dateStr:', dateStr);
    
    this.setData({
      'formData.meetingDate': dateStr,
      showDatePicker: false
    });
  },

  /**
   * 取消选择日期
   */
  onDateCancel() {
    this.setData({
      showDatePicker: false
    });
  },

  /**
   * 显示时间选择器
   */
  showTimePicker() {
    // 获取当前时间并设置选择器的默认值
    const currentTime = this.data.formData.meetingTime;
    if (currentTime) {
      const parts = currentTime.split(':');
      const hour = parts[0];
      const minute = parts[1];
      
      const hourIndex = this.data.timeHours.indexOf(hour);
      const minuteIndex = this.data.timeMinutes.indexOf(minute);
      
      this.setData({
        currentTimeValue: [
          hourIndex >= 0 ? hourIndex : 9, // 默认09:00
          minuteIndex >= 0 ? minuteIndex : 0 // 默认00分
        ],
        showTimePicker: true
      });
    } else {
      // 默认09:00
      this.setData({
        currentTimeValue: [9, 0],
        showTimePicker: true
      });
    }
  },

  /**
   * 时间选择器滚动变化
   */
  onTimeChange(event) {
    const { value } = event.detail;
    this.setData({
      currentTimeValue: value
    });
  },

  /**
   * 确认选择时间
   */
  onTimeConfirm() {
    const currentTimeValue = this.data.currentTimeValue;
    const hourIndex = currentTimeValue[0];
    const minuteIndex = currentTimeValue[1];
    
    const hour = this.data.timeHours[hourIndex];
    const minute = this.data.timeMinutes[minuteIndex];
    
    console.log('onTimeConfirm - hourIndex:', hourIndex, 'minuteIndex:', minuteIndex);
    console.log('onTimeConfirm - hour:', hour, 'minute:', minute);
    console.log('onTimeConfirm - timeHours:', this.data.timeHours);
    console.log('onTimeConfirm - timeMinutes:', this.data.timeMinutes);
    
    const timeStr = `${hour}:${minute}`;
    console.log('onTimeConfirm - timeStr:', timeStr);
    
    this.setData({
      'formData.meetingTime': timeStr,
      showTimePicker: false
    });
  },

  /**
   * 取消选择时间
   */
  onTimeCancel() {
    this.setData({
      showTimePicker: false
    });
  },

  /**
   * 显示人数选择器
   */
  showCountPicker() {
    // 获取当前选中的索引
    const currentValue = this.data.formData.participantCount;
    const currentIndex = this.data.countOptions.indexOf(currentValue);
    
    this.setData({
      showCountPicker: true,
      currentCountIndex: currentIndex >= 0 ? currentIndex : 0
    });
  },

  /**
   * 人数选择器滚动变化
   */
  onCountChange(event) {
    const { value } = event.detail;
    this.setData({
      currentCountIndex: value[0]
    });
  },

  /**
   * 确认选择人数
   */
  onCountConfirm() {
    const selectedIndex = this.data.currentCountIndex;
    const selectedValue = this.data.countOptions[selectedIndex];
    
    this.setData({
      'formData.participantCount': selectedValue,
      showCountPicker: false
    });
  },

  /**
   * 取消选择人数
   */
  onCountCancel() {
    this.setData({
      showCountPicker: false
    });
  },

  /**
   * 生成会议纪要
   */
  generateMeetingMinutes() {
    const { formData } = this.data;
    
    // 验证必填字段
    if (!formData.meetingTitle.trim()) {
      wx.showToast({
        title: '请输入会议主题',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.meetingContent.trim()) {
      wx.showToast({
        title: '请输入会议内容',
        icon: 'none'
      });
      return;
    }

    // 构建AI提示内容
    const prompt = this.buildPrompt(formData);
    
    // 直接跳转到聊天页面，让聊天页面处理API调用
    wx.navigateTo({
      url: `/pages/chat/chat?query=${encodeURIComponent(prompt)}&functionType=meeting_summary&title=会议纪要生成`
    });
  },

  /**
   * 构建AI提示内容
   */
  buildPrompt(formData) {
    let prompt = `请为以下会议生成专业的会议纪要：\n\n`;
    
    prompt += `【会议基本信息】\n`;
    prompt += `会议主题：${formData.meetingTitle}\n`;
    
    if (formData.meetingDate) {
      prompt += `会议日期：${formData.meetingDate}\n`;
    }
    
    if (formData.meetingTime) {
      prompt += `会议时间：${formData.meetingTime}\n`;
    }
    
    if (formData.participantCount) {
      prompt += `参会人数：${formData.participantCount}\n`;
    }
    
    prompt += `\n【会议内容】\n${formData.meetingContent}\n`;
    
    if (formData.keyPoints) {
      prompt += `\n【重点讨论】\n${formData.keyPoints}\n`;
    }
    
    if (formData.decisions) {
      prompt += `\n【会议决议】\n${formData.decisions}\n`;
    }
    
    if (formData.actionItems) {
      prompt += `\n【行动计划】\n${formData.actionItems}\n`;
    }
    
    prompt += `\n请生成格式规范、内容完整的会议纪要，包括会议概况、讨论要点、决议事项、后续行动等部分。`;
    
    return prompt;
  },

  /**
   * 重置表单
   */
  resetForm() {
    wx.showModal({
      title: '确认重置',
      content: '确定要清空所有输入内容吗？',
      success: (res) => {
        if (res.confirm) {
          const today = new Date();
          const month = today.getMonth() + 1;
          const day = today.getDate();
          const monthStr = month < 10 ? '0' + month : month;
          const dayStr = day < 10 ? '0' + day : day;
          const dateStr = `${today.getFullYear()}-${monthStr}-${dayStr}`;
          
          this.setData({
            formData: {
              meetingTitle: '',
              meetingDate: dateStr,
              meetingDateValue: today.getTime(),
              meetingTime: '',
              meetingTimeValue: new Date().getTime(),
              participantCount: '',
              meetingContent: '',
              keyPoints: '',
              decisions: '',
              actionItems: ''
            }
          });
        }
      }
    });
  }
});
